package com.deepalhome.deepalclub

import android.os.Bundle
import android.sun.security.provider.JavaKeyStoreProvider
import android.view.Gravity
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.Task
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.deepalhome.deepalclub.adb.AdbConnectionManager
import com.deepalhome.deepalclub.databinding.ActivityMain1Binding
import io.github.muntashirakon.adb.AdbStream
import io.github.muntashirakon.adb.LocalServices
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import java.security.Security


const val KEY_HOST = "KEY_HOST"

class MainActivityB : AppCompatActivity() {
    private lateinit var binding: ActivityMain1Binding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Security.addProvider(JavaKeyStoreProvider())
        ToastUtils.getDefaultMaker().setGravity(Gravity.CENTER, 0, 0)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.ipEt.setText(SPUtils.getInstance().getString(KEY_HOST, ""))
        binding.connectBtn.setOnClickListener {
            ThreadUtils.executeBySingle(object : Task<String>() {
                override fun doInBackground(): String {
                    val ip = binding.ipEt.text.toString()
                    if (!RegexUtils.isIP(ip)) {
                        return "请输入正确IP！"
                    }
                    saveIp(ip)
                    val port = binding.portEt.text.toString()
                    return try {
                        if (AdbConnectionManager.connect(ip, port.toInt())) {
                            "连接成功！"
                        } else {
                            "连接失败！"
                        }
                    } catch (e: Exception) {
                        when (e.message) {
                            "Connection failed" -> "连接失败，请检查后网络和输入后重试"
                            "ADB pairing is required." -> "请先完成配对操作"
                            else -> e.message ?: "未知错误，请检查后网络和输入后重试"
                        }
                    }
                }

                override fun onCancel() {
                }

                override fun onFail(t: Throwable) {
                }

                override fun onSuccess(result: String) {
                    ToastUtils.showLong(result)
                }
            })
        }
        binding.pairBtn.setOnClickListener {
            ThreadUtils.executeBySingle(object : Task<String>() {
                override fun doInBackground(): String {
                    val ip = binding.ipEt.text.toString()
                    if (!RegexUtils.isIP(ip)) {
                        return "请输入正确IP！"
                    }
                    saveIp(ip)
                    val code = binding.codeEt.text.toString()
                    if (code.isBlank()) {
                        return "请输入正确配对码！"
                    }
                    val port = binding.portEt.text.toString()
                    return try {
                        if (AdbConnectionManager.pair(ip, port.toInt(), code)) {
                            "配对成功！"
                        } else {
                            "配对失败！"
                        }
                    } catch (e: Exception) {
                        e.message ?: "未知错误"
                    }
                }

                override fun onCancel() {
                }

                override fun onFail(t: Throwable) {
                }

                override fun onSuccess(result: String) {
                    ToastUtils.showLong(result)
                }
            })
        }
        binding.autoBtn.setOnClickListener {
            try {
                val ip = binding.ipEt.text.toString()
                if (!RegexUtils.isIP(ip)) {
                    ToastUtils.showLong("请输入正确IP！")
                    return@setOnClickListener
                }
                val result = AdbConnectionManager.autoConnect(Utils.getApp(), 10000)
                if (result) {
                    ToastUtils.showLong("连接成功")
                } else {
                    ToastUtils.showLong("连接失败")
                }
            } catch (e: Exception) {
                ToastUtils.showLong(e.message)
            }
        }
        binding.resetAppStoreBtn.setOnClickListener {
            execute("am force-stop com.x.live")
        }
    }

    private fun saveIp(ip: String) {
        SPUtils.getInstance().put(KEY_HOST, ip)
    }

    private val outputGenerator = Runnable {
        try {
            BufferedReader(InputStreamReader(adbStream?.openInputStream())).use { reader ->
                var s: String?
                while (reader.readLine().also { s = it } != null) {
                    val sb = StringBuilder()
                    sb.append(s).append("\n")
                    ThreadUtils.runOnUiThread {
                        ToastUtils.showLong(sb)
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    private var adbStream: AdbStream? = null
    private fun execute(command: String) {
        ThreadUtils.executeBySingle(object : Task<String>() {
            override fun doInBackground(): String {
                return try {
                    if (adbStream == null) {
                        adbStream = AdbConnectionManager.openStream(LocalServices.SHELL)
                        Thread(outputGenerator).start()
                    }
                    adbStream?.openOutputStream()?.use { os ->
                        os.write(
                            String.format("%1\$s\n", command).toByteArray(StandardCharsets.UTF_8)
                        )
                        os.flush()
                        os.write("\n".toByteArray(StandardCharsets.UTF_8))
                    }
                    ""
                } catch (e: java.lang.Exception) {
                    e.message ?: "未知错误"
                }
            }

            override fun onCancel() {
            }

            override fun onFail(t: Throwable?) {
            }

            override fun onSuccess(result: String?) {

            }
        })
    }
}